<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../react18/react.development.js"></script>
    <script src="../react18/react-dom.development.js"></script>
    <script src="../react18/babel.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="text/babel">
      /*
        收集表单数据-受控组件
          * 首先在状态中初始化所有的表单的数据
          * 把数据通过value或者checked等属性强制绑定给表单元素
          * 给表单元素绑定onChange事件,在事件函数中获取当前表单的最新内容或者最新状态(e.target),然后通过setState的方式在修改对应的状态
          * 我们在最后收集表单数据的时候,直接拿状态中的数据即可
      */
      class App extends React.Component {
        state = {
          username: "",
          password: "",
          isAgree: false,
        };
        render() {
          const { username, password, isAgree } = this.state;
          return (
            <form action="">
              <p>
                请输入用户名
                <input
                  type="text"
                  value={username}
                  onChange={this.usernameChange}
                />
              </p>
              <p>
                请输入密码
                <input
                  type="text"
                  value={password}
                  onChange={this.passwordChange}
                />
              </p>
              <p>
                请输入协议
                <input
                  type="text"
                  checked={isAgree}
                  onChange={this.checkChange}
                />
              </p>
              <button onClick={this.formSubmit}>提交</button>
            </form>
          );
        }
        formSubmit = (e) => {
          //阻止默认事件
          e.preventDefault();

          console.log("用户名", this.state.username);
          console.log("密码", this.state.password);
        };
        passwordChange = (e) => {
          console.log("passwordChange", e.target.value);
          this.setState({ password: e.target.value });
        };

        usernameChange = (e) => {
          console.log("usernameChange", e.target.value);
          this.setState({ username: e.target.value });
        };

        checkChange = (e) => {
          // console.log(e.target.checked);
          this.setState({ isAgree: e.target.checked });
        };
      }

      ReactDOM.createRoot(document.getElementById("app")).render(<App />);
    </script>
  </body>
</html>
